/**
 * @description 商品分类
 */
import style from './styles/App.less';
import React from 'react';

const Fragment = React.Fragment;
import TabBar from "components/TabBar";
import EntryBase from "../Common/EntryBase";
import CategoryGoodsItem from "components/CategoryGoodsItem";
import ScrollReachEndContainer from "components/ScrollReachEndContainer";
import { Toast, Dialog } from "wd-mobile";
//工具
import classnames from "classnames";
import util from "commons/util";
//img
import icon_search from "images/icon/search.png";
//api
import { list as typeList } from "api_liuhaojie/app/type";
import { list as goodsListForType, bookGoods, unBookGoods } from "api_liuhaojie/app/goods";
import { search_tips ,classification_banner} from "api_xukaiyu/app/content";

export class App extends EntryBase {
    constructor() {
        super();
        this.state = {
            // 分类列表
            typeList: [],
            // 商品列表
            goodsList: [],
            // 商品列表页数
            goodsListPage: 1,
            // 分类key
            typeKey: 0,
            typeIndex:0,
            bannerImg:{}
        }
        this.categoryRef = React.createRef();
        this.categoryGoodsListRef = React.createRef();
        this.mainRef = React.createRef();
        this.categoryContainerHeight=0;
        this.loading = true;
    }
    componentDidMount() {
        super.componentDidMount();
        this.categoryContainerHeight= window.innerHeight - 100 - 108 ;
        this.categoryRef.current.containerRef.current.style.height = this.categoryContainerHeight+'px';
        this.categoryGoodsListRef.current.containerRef.current.style.height = this.categoryContainerHeight-206+'px';

        //推荐位置banner
        classification_banner().then(data=>{
            this.setState({
                bannerImg:data.data[0]||{}
            })    
        })
        // 搜索提示
        search_tips().then(res => {
            this.setState({
                search_tips: res.data
            })
        })
        // 查询分类
        typeList().then(res => {
            this.setState({
                typeList: res.data || []
            }, () => {
                // 分类历史点击记录
                const history_typeKey = sessionStorage.getItem("history_typeKey");
                const history_typeKey_index = sessionStorage.getItem("history_typeKey_index");
                if (history_typeKey && history_typeKey_index) {
                    const scrollContainerRef = this.mainRef.current.containerRef.current;
                    scrollContainerRef.scrollTop = 1000;
                    const scrollCategoryRef = this.categoryRef.current.containerRef.current;
                    if (this.state.typeList.length - 4 < history_typeKey_index) {
                        scrollCategoryRef.scrollTop = 1000;
                    }
                }
                let typeKey = history_typeKey || res.data[0]["key"];
                let typeKeyIndex = history_typeKey_index || 0;

                // 查询分类下商品
                this.goodsListForType(typeKey, typeKeyIndex);
            })
        })
    }

    // 查询分类商品列表
    goodsListForType(typeKey, index, type) {
        if(typeKey=='RECOMMEND'){
            this.categoryGoodsListRef.current.containerRef.current.style.height = this.categoryContainerHeight-206+'px';
        }else{
            this.categoryGoodsListRef.current.containerRef.current.style.height = this.categoryContainerHeight+'px';
        }
        Toast.loading("", 60000);
        this.loading = true;
        this.setState({
            scrollLoadText: "正在加载更多商品...",
        })
        goodsListForType({
            goodsType: typeKey,
            page: this.state.goodsListPage
        }).then((res) => {
            Toast.destroy();
            let goodsList = [];
            if (this.state.typeKey != typeKey) {
                // 如果是切换类型，list数据需要重置
                goodsList = res.data;
            } else {
                // 如果是同类型，list是追加数据
                goodsList = [...this.state.goodsList, ...res.data];
            }
            this.setState({
                goodsListPage: res.data.length < 1 ? this.state.goodsListPage : this.state.goodsListPage + 1,
                goodsList: goodsList,
                scrollLoadText: res.data.length < 10 ? "没有更多商品" : "正在加载更多商品..."
            }, () => {
                // 如果切换分类，优化滚动距离
                if (this.state.typeKey != typeKey) {
                    // 滚动后设置分类
                    this.setState({
                        typeKey: typeKey,
                        typeIndex:index||0
                    })

                    // 记录点击位置，并且把商品列表容器滚动回顶部
                    if (type == "click") {
                        sessionStorage.setItem("history_typeKey", typeKey);
                        sessionStorage.setItem("history_typeKey_index", index);
                        const scrollContainerRef = this.categoryGoodsListRef.current.containerRef.current;
                        scrollContainerRef.scrollTop = 0;
                    }
                }
                this.loading = false;
            })
        })
    }

    // 触底
    reachEnd() {
        if (!this.loading) {
            this.goodsListForType(this.state.typeKey)
        }
    }



    render() {
        let {bannerImg}=this.state;
        return (<div className={style.categorys} >
            <div className={classnames(style.searchBar, {
                [style.searchBarStateTwo]: this.state.searchBarStateTwo
            })}>
                <div className={classnames(style.searchBarWrapper, "wdskeleton-ignore")} onClick={() => {
                    util.go("search.html");
                }}><img src={icon_search} />{this.state.search_tips || "请输入关键字搜索"}</div>
            </div>
            <ScrollReachEndContainer ref={this.mainRef} className={classnames("x-scroll-y")} showScrollLoadText={false}>
            <div className={style.categoryGoods}>
                <div className={style.categoryContainer}>
                    <ScrollReachEndContainer canScroll={this.state.typeListCanScroll} className={classnames(style.category)} ref={this.categoryRef} showScrollLoadText={false}>
                        {
                            this.state.typeList.map((item, index) => {
                                return (
                                    <div className={classnames(style.categoryItem, {
                                        [style["category-active"]]: this.state.typeKey == item.key
                                    })} key={item.key} onClick={() => {
                                        // 分类不同才会触发切换
                                        if (this.state.typeKey != item.key) {
                                            this.setState({
                                                goodsListPage: 1
                                            }, () => {
                                                // 查询分类下商品
                                                this.goodsListForType(item.key, index, "click")
                                            })
                                        }
                                    }}>
                                        <div className={classnames(style.categoryTag)}><span>{item.value}</span></div>
                                    </div>
                                )
                            })
                        }
                    </ScrollReachEndContainer>
                    <div>
                        <div hidden={this.state.typeIndex!=0} className={style.recommondBanner} onClick={()=>{bannerImg.linkUrl&&(location.href=`${bannerImg.linkUrl}`)}}><img src={bannerImg.bannerPic}/></div>
                        <ScrollReachEndContainer canScroll={this.state.typeListCanScroll} ref={this.categoryGoodsListRef} className={style.categoryGoodsList} loadText={this.state.scrollLoadText} onReachEnd={() => {
                            this.reachEnd();
                        }}>
                            {
                                this.state.goodsList.map((item, index) => {
                                    return (
                                        <CategoryGoodsItem key={index} data={item} isHot={this.state.typeKey == "RECOMMEND" && index < 3&&item.stockNum>0} bookGoods={() => {
                                            bookGoods({
                                                skuId: item.id
                                            }).then(res => {
                                                const newGoodsList = [...this.state.goodsList];
                                                newGoodsList[index].isBook = true;
                                                this.setState({
                                                    goodsList: newGoodsList
                                                })
                                            })
                                        }} unBookGoods={() => {
                                            unBookGoods({
                                                skuId: item.id
                                            }).then(res => {
                                                const newGoodsList = [...this.state.goodsList];
                                                newGoodsList[index].isBook = false;
                                                this.setState({
                                                    goodsList: newGoodsList
                                                })
                                            })
                                        }} />
                                    )
                                })
                            }
                            
                        </ScrollReachEndContainer>
                    </div>
                </div>
            </div>
            </ScrollReachEndContainer>
            <TabBar activeIndex={1} />
        </div>
        );
    }
}

export default App;